import {Component, ViewChild} from '@angular/core';
import {NavController, Content} from 'ionic-angular';
import {HttpService} from '../../providers/HttpService';
import {NativeServiceC} from "../../providers/NativeServiceC";
import {GlobalData} from "../../providers/GlobalData";

import {SearchShopPage} from './searchShop/searchShop'

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: []
})
export class HomePage {

    channels:Array<{
        editable:boolean,
        id:number,
        name:string
    }>;
    editChannels = [];
    items = [];
    nextUrl:string = '';
    isRefresh:boolean = true;
    constructor(public navCtrl:NavController,
                private httpService:HttpService,
                private nativeService:NativeServiceC,
                private globalData:GlobalData) {
    }

    ionViewDidLoad() {
        this.getChannels();
    }

    changeChannel(channel,index){
        this.isRefresh = true;
        let url = '/v1/channels/' + channel.id + '/items';
        this.getItems(url);
    }

    // 加载更多
    doInfinite(event){
        this.getItems(this.nextUrl,{},event);
    }

    search(){
        this.navCtrl.push(SearchShopPage);
    }

    homeCellClick(index){
        console.log('cell组件通信',index);
    }
    homeLikeClick(index){
        console.log('like组件通信',index);
    }

    private getChannels() {
        const channelUrl = '/v2/channels/preset';
        let sender = {
            gender: 1,
            generation: 1
        };
        this.httpService.get(channelUrl, sender)
            .subscribe(res => {
                this.channels = res.channels;
                this.editChannels = res.candidates;
                let url = '/v1/channels/' + this.channels[0].id + '/items';
                this.getItems(url);
            })
    }

    private getItems(url:string,sender?:Object,infiniteScroll?) {
        sender = sender || {
            gender: 1,
            generation: 1,
            limit: 20,
            offset: 0
        };
        if (!this.isRefresh){
            this.globalData.showLoading = false;
        }
        this.httpService.get(url, sender).subscribe(res => {
            this.nativeService.hideLoading();
            if (this.isRefresh) this.items.length = 0;
            this.items = this.items.concat(res.items);
            this.nextUrl = res.paging.next_url;
            this.isRefresh = false;
            console.log(res);
            infiniteScroll && infiniteScroll.complete();
        })
    }

}
